package com.atguigu.gulimall.auth.web;

import com.alibaba.fastjson.JSON;
import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.utils.HttpUtils;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.auth.feign.MemberFeignService;
import com.atguigu.common.vo.MemberRespVo;
import com.atguigu.gulimall.auth.vo.SocialUser;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author baiWT
 * @Description
 * @Date 2022/4/6 16:08
 **/
@Controller
public class OAuth2Controller {

    @Resource
    private MemberFeignService memberFeignService;

    @GetMapping("/oauth2.0/weibo/success")
    public String weibo(@RequestParam("code") String code, HttpSession session) throws Exception {
        Map<String,String> header = new HashMap<>();
        Map<String,String> query = new HashMap<>();

        Map<String,String> map = new HashMap<>();
        map.put("client_id","4063212089");
        map.put("client_secret","a8cec905d1c826d7ee3c40db80c984d8");
        map.put("grant_type","authorization_code");
        map.put("redirect_uri","http://auth.gulimall.com/oauth2.0/weibo/success");
        map.put("code",code);

        //根据code换取accessToken
        HttpResponse response = HttpUtils.doPost("https://api.weibo.com","/oauth2/access_token","post",header,query,map);

        //处理
        if (response.getStatusLine().getStatusCode() == 200){
            //获取到了accessToken
            String json = EntityUtils.toString(response.getEntity());
            SocialUser socialUser = JSON.parseObject(json, SocialUser.class);

            //知道那个是社交用户
            //登录或者注册社交用户
            R r = memberFeignService.oauthLogin(socialUser);
            if (r.getCode() == 0){
                MemberRespVo vo = r.getData("data", MemberRespVo.class);
                System.out.println("登录成功:"+vo);
                //1、解决子域session共享问题
                //2、使用json的序列化方式存储
                session.setAttribute(AuthServerConstant.LOGIN_USER,vo);
                return "redirect:http://gulimall.com";
            }else {
                return "redirect:http://auth.gulimall.com/login.html";
            }
        }else {
            return "redirect:http://auth.gulimall.com/login.html";
        }
    }
}
